<template>
  <div class="app-container customer-div">
    <div style="margin-top: 40px">
      <!--搜索-->
      <el-form :inline="true" :model="listQuery" size="mini" label-width="120px">
        <el-form-item label="采购订单号：">
          <el-input v-model="listQuery.orderSn" clearable></el-input>
        </el-form-item>
        <el-form-item label="采购日期：">
          <el-date-picker
                  :default-time="['00:00:00', '23:59:59']"
                  v-model="listQuery.createTime"
                  type="daterange"
                  format="yyyy 年 MM 月 dd 日"
                  value-format="yyyy-MM-dd"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="供应商：">
          <el-select
                  clearable
                  v-model="listQuery.supplierId"
                  filterable
                  reserve-keyword
                  placeholder="请输入关键词"
                  style="width: 220px;">
            <el-option
                    v-for="item in options2"
                    :key="item.supplierId"
                    :label="item.supplierName"
                    :value="item.supplierId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="合同公司：">
          <el-input v-model="listQuery.fromCompany" style="width: 220px;" clearable></el-input>
        </el-form-item>
        <el-form-item label="品名：">
          <el-input v-model="listQuery.goodsName" clearable></el-input>
        </el-form-item>

        <el-form-item label="牌号：">
          <el-autocomplete
            clearable
            style="width:300px;"
            class="inline-input"
            v-model="listQuery.goodsSn"
            :fetch-suggestions="querySearchGoodsSn"
            placeholder="请输入内容"
            @select="handleSelectGoodsSn"
          >
            <template slot-scope="{ item }">
              <div>{{ item.goodsSn }}</div>
            </template>
          </el-autocomplete>
        </el-form-item>

        <el-form-item label="业务员：" >
          <el-select v-model="listQuery.purchaseUserId" filterable placeholder="请选择" clearable>
            <el-option
                    v-for="item in userOptionList"
                    :key="item.userId"
                    :label="item.userName"
                    :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="采购员：" >
          <el-select v-model="listQuery.buyerUserId" filterable placeholder="请选择" clearable>
            <el-option
                    v-for="item in userOptionList"
                    :key="item.userId"
                    :label="item.userName"
                    :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="付款状态：" >
          <el-select v-model="listQuery.payState" filterable placeholder="请选择" clearable>
            <el-option key="0" label="未付款" value="0"></el-option>
            <el-option key="1" label="部分付款" value="1"></el-option>
            <el-option key="2" label="已付款" value="2"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="入库状态："  >
          <el-select v-model="listQuery.goodsInState" filterable placeholder="请选择" clearable>
            <el-option :key="0" label="未入库" :value="0"></el-option>
            <el-option :key="1" label="部分入库" :value="1"></el-option>
            <el-option :key="2" label="已入库" :value="2"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="安排提货状态："  >
          <el-select v-model="listQuery.goodsTakeState" filterable placeholder="请选择" clearable>
            <el-option :key="0" label="未安排提货" :value="0"></el-option>
            <el-option :key="1" label="已部分安排提货" :value="1"></el-option>
            <el-option :key="2" label="已安排全部提货" :value="2"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="财务状态："  >
          <el-select v-model="listQuery.financeState" filterable placeholder="请选择" clearable>
            <el-option :key="0" label="未审核" :value="0"></el-option>
            <el-option :key="1" label="已审核" :value="1"></el-option>
            <el-option :key="2" label="已关闭" :value="2"></el-option>
            <el-option :key="3" label="部分审核" :value="3"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button
            @click="handleSearchList()"
            type="primary">
            查询
          </el-button>

          <el-button
                  v-if="contractDetailedExport"
                  :loading="btnloading"
                  @click="downloadExcel()"
                  type="primary">
            导出
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <div style="font-size:14px;line-height: 30px;padding:10px 0 ">
      合同金额：<span style="font-weight: bold">{{statisticsAmount}}</span>
      <span style="padding-left:20px;">商品数量：</span><span style="font-weight: bold">{{statisticsGoodsNum}}</span>
      <span style="padding-left:20px;">采购实际数量：</span><span style="font-weight: bold">{{authNum}}</span>
      <span style="padding-left:20px;">关闭数量：</span><span style="font-weight: bold">{{closeNum}}</span>
      <span style="padding-left:20px;">采购实际金额：</span><span style="font-weight: bold">{{authPrice}}</span>
    </div>

      <!--数据列表-->
    <div class="table-container">
        <el-table
          :header-cell-style="{'text-align':'center'}"
          v-loading="listLoading"
          :data="tableData"
          border
          style="width: 100%; margin-top: 20px">
          <el-table-column
                  label="采购日期"
                  width="100"
                  align="center">
            <template slot-scope="scope">
              {{scope.row.createTime}}
            </template>
          </el-table-column>
          <el-table-column  label="采购订单号" width="150" align="center">
            <template slot-scope="scope">
              <el-link @click="toDetail(scope.row)" type="primary" style="font-size:12px">
                {{scope.row.orderSn}}
              </el-link>

            </template>
          </el-table-column>
          <el-table-column
                  label="供应商名称"
                  width="200">
            <template slot-scope="scope">
              {{scope.row.supplierName}}
            </template>
          </el-table-column>
          <el-table-column
                  label="合同公司"
                  width="100"
                  align="center">
            <template slot-scope="scope">
              {{scope.row.fromCompany}}
            </template>
          </el-table-column>
          <el-table-column
                  label="交货日期"
                  width="100"
                  align="center">
            <template slot-scope="scope">
              {{scope.row.sendDate}}
            </template>
          </el-table-column>
          <el-table-column
                  label="交货方式"
                  width="150"
                  align="center">
            <template slot-scope="scope">
              {{scope.row.sendType}}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="采购单价"
            width="100">
            <template slot-scope="scope">
              {{scope.row.goodsPrice}}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="采购数量"
            width="100">
            <template slot-scope="scope">
              {{scope.row.goodsNum}}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="采购金额"
            width="100">
            <template slot-scope="scope">
              {{scope.row.goodsAmount}}
            </template>
          </el-table-column>
          <el-table-column
                  label="品名"
                  width="150"
                  align="center">
            <template slot-scope="scope">
              {{scope.row.goodsName}}
            </template>
          </el-table-column>
          <el-table-column
                  align="center"
                  label="牌号"
                  width="150">
            <template slot-scope="scope">
              {{scope.row.goodsSn}}
            </template>
          </el-table-column>
          <el-table-column
                  align="center"
                  label="采购员"
                  width="100">
            <template slot-scope="scope">
                {{scope.row.buyerUserName}}
            </template>
          </el-table-column>

          <el-table-column
            align="center"
            label="关闭数量"
            width="100">
            <template slot-scope="scope">
              {{scope.row.goodsUnNum}}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="采购实际数量"
            width="100">
            <template slot-scope="scope">
              {{scope.row.goodsAuthNum}}
            </template>
          </el-table-column>
          <el-table-column
                  align="center"
                  label="采购单位"
                  width="80">
            <template slot-scope="scope">
              {{scope.row.goodsUnit}}
            </template>
          </el-table-column>

          <el-table-column
                  align="center"
                  label="杂费(装卸费)"
                  width="100">
            <template slot-scope="scope">
              {{scope.row.goodsConsultation}}
            </template>
          </el-table-column>
          <el-table-column
            label="发货方式"
            width="150"
            align="center">
            <template slot-scope="scope">
              {{scope.row.deliveryType}}
            </template>
          </el-table-column>
          <el-table-column
            label="结算方式"
            width="150"
            align="center">
            <template slot-scope="scope">
              {{scope.row.settleType}}
            </template>
          </el-table-column>

          <el-table-column
                  align="center"
                  label="付款状态"
                  width="100">
            <template slot-scope="scope">
              {{scope.row.payState | fifpayState}}
            </template>
          </el-table-column>
          <el-table-column
                  align="center"
                  label="销售采购毛利"
                  width="100">
            <template slot-scope="scope">
              {{ scope.row.perProfit }}
            </template>
          </el-table-column>
          <el-table-column
                  align="center"
                  label="入库数量"
                  width="100">
            <template slot-scope="scope">
              {{scope.row.goodsInNum}}
            </template>
          </el-table-column>
          <el-table-column
                  align="center"
                  label="未入库数量"
                  width="100">
            <template slot-scope="scope">
              {{scope.row.goodsUnInNum}}
            </template>
          </el-table-column>
          <el-table-column
                  align="center"
                  label="提货状态"
                  width="100">
            <template slot-scope="scope">
              {{scope.row.goodsTakeState}}
            </template>
          </el-table-column>
          <el-table-column
                  align="center"
                  label="已提货数量"
                  width="100">
            <template slot-scope="scope">
              {{scope.row.goodsTakeNum}}
            </template>
          </el-table-column>
          <el-table-column
                  align="center"
                  label="未提货数量 "
                  width="100">
            <template slot-scope="scope">
              {{scope.row.goodsUnTakeNum}}
            </template>
          </el-table-column>
          <el-table-column
            label="备注"
            width="200">
            <template slot-scope="scope">
                 {{scope.row.goodsRemark}}
            </template>
          </el-table-column>
          <el-table-column
                  align="center"
                  label="业务员"
                  width="100">
            <template slot-scope="scope">
              {{scope.row.userName}}
            </template>
          </el-table-column>

          <el-table-column
            width="150"
            fixed="right"
            label="操作"
            align="center">
            <template slot-scope="scope">
              <el-button
                style="margin-left:0"
                type="text"
                size="mini"
                @click="showpop(scope.row)">修改提货数量
              </el-button>
              <el-button
                v-if="changePurchaseDetailRemark"
                style="margin-left:0"
                type="text"
                size="mini"
                @click="showRemark(scope.row)">修改备注并推送金蝶
              </el-button>
              <el-button
                style="margin-left:0"
                type="text"
                size="mini"
                @click="showList(scope.row)">排货记录
              </el-button>
            </template>
          </el-table-column>

        </el-table>
      </div>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :current-page.sync="listQuery.pageNum"
        :page-size="listQuery.pageSize"
        :page-sizes="[10,15,20]"
        :total="count">
      </el-pagination>
    </div>

    <!--编辑提货备注-->
    <el-dialog
      title="修改提货数量"
      :visible.sync="dialogVisible"
      width="500px">
      <el-form :model="sendForm" size="mini" label-width="100px" ref="sendForm">
        <el-form-item label="提货数量：">
          <el-input-number v-model="sendForm.num" :min="0" :max="sendForm.max"></el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="handleConfirm" :loading="btnLoading2">确 定</el-button>
      </span>
    </el-dialog>

    <!--修改商品行备注-->
    <el-dialog
      :close-on-click-modal="false"
      :beforeClose="handleClose5"
      title="填写备注"
      :visible.sync="dialogVisible5"
      width="400px">
      <el-form :model="changeRemarkFrom" size="mini" label-width="100px"  ref="changeRemarkFrom" :rules="rules5">
        <el-form-item label="备注：" prop="goodsRemark">
          <el-input v-model="changeRemarkFrom.goodsRemark" :autosize="{ minRows: 2, maxRows: 6}" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose5">取 消</el-button>
          <el-button type="primary" @click="handleConfirm5" :loading="btnLoading6">确 定</el-button>
      </span>
    </el-dialog>

    <!--采购排货记录-->
    <el-dialog
      :close-on-click-modal="false"
      title="排货记录"
      :visible.sync="dialogVisible6"
      width="800px">
      <el-table
        :header-cell-style="{'text-align':'center'}"
        v-loading="phlistLoading"
        :data="phlist"
        border
        style="width: 100%; margin-top: 20px">
        <el-table-column
          label="订单号"
          width="150"
          align="center">
          <template slot-scope="scope">
                {{scope.row.billSn}}
          </template>
        </el-table-column>
        <el-table-column
          label="排货商品">
          <template slot-scope="scope">
            <div v-for="(item,index) in scope.row.billGoods" class="mergeDiv" style="text-align: left" :style="{'padding-top':index == 0 ? '0' : '13px','padding-bottom':index <scope.row.billGoods.length - 1 ? '13px' : '0px' }">{{item.goodsName}} / {{item.goodsSn}} / {{item.goodsNum}}</div>
          </template>
        </el-table-column>
        <el-table-column
          label="提货日期"
          width="100"
          align="center">
          <template slot-scope="scope">
            {{scope.row.takeTime}}
          </template>
        </el-table-column>
        <el-table-column
          label="提货数量"
          width="100"
          align="center">
          <template slot-scope="scope">
            {{scope.row.billTakeNum}}
          </template>
        </el-table-column>
        <el-table-column
          label="提货仓库"
          width="100"
          align="center">
          <template slot-scope="scope">
            {{scope.row.takeWarehouse}}
          </template>
        </el-table-column>
        <el-table-column
          label="排货状态"
          width="100"
          align="center">
          <template slot-scope="scope">
            {{scope.row.planState | fifplanstatus}}
          </template>
        </el-table-column>

      </el-table>
    </el-dialog>

  </div>
</template>
<script>
  import {getCustomerOption,getOrderUsersList,purchaseOrderGoodsList,supplierList,orderGoodsList,changeDetailRemarkPurchase,planGoodsList} from '@/api/partner'
  import {goodsList} from '@/api/company'
  import {formatDate} from '@/utils/date';
  import store from '@/store'
  import { mapGetters } from 'vuex'
  import {changePlanNum} from "../../api/partner";
  const defaultListQuery={
    pageNum: 1,
    pageSize: 10,
    supplierId: '',
    purchaseUserId:'',
    fromCompany:'',
    createTime:null,
    orderSn:'',
    buyerUserId:'',
    goodsInState:null,
    goodsTakeState:null,
    financeState:null,
    goodsName:'',
    goodsSn:'',
    kingGoodsId:'',
  };

  const defaultSendForm={
    num:'',
    max:'',
  };

  const defauleChangeRemarkFrom={
    pogId:'',
    goodsRemark:'',
  }

  export default {
    name: "index",
    data(){
      return {
        listQuery: JSON.parse(JSON.stringify(defaultListQuery)),
        tableData: [],
        count: 0,
        listLoading: false,
        userOptionList:[],
        roles:store.getters.roles ? store.getters.roles : [],
        totalNum:0,
        totalAmount:0,
        loading:false,
        options:[],
        loading2:false,
        options2:[],
        statisticsAmount:'',
        statisticsGoodsNum:'',
        btnloading:false,
        goodsList:[],

        dialogVisible:false,
        sendForm:JSON.parse(JSON.stringify(defaultSendForm)),
        btnLoading2:false,

        changeRemarkFrom:JSON.parse(JSON.stringify(defauleChangeRemarkFrom)),
        dialogVisible5:false,
        btnLoading6:false,
        rules5:{
          goodsRemark:[{required: true, trigger: 'blur' ,message: '请输入备注',}],
        },

        dialogVisible6:false,
        phlistLoading:false,
        phlist:[],
        authNum:'',
        closeNum:'',
        authPrice:''
      }
    },
    computed: {
      ...mapGetters([
        'name',
        'mobile',
        'userId',
        'isMange',
      ]),
      contractDetailedExport(){
        if(this.roles.indexOf("contractDetailedExport") != -1){
          return true
        }else{
          return false
        }
      },
      changePurchaseDetailRemark(){
        if(this.roles.indexOf("changePurchaseDetailRemark") != -1){
          return true
        }else{
          return false
        }
      },
    },
    created() {
      let now = new Date();
      let nowMonth = now.getMonth(); //当前月
      let nowYear = now.getFullYear(); //当前年
      //本月的开始时间
      let monthStartDate = new Date(nowYear, nowMonth, 1);
      //本月的结束时间
      let monthEndDate = new Date(nowYear, nowMonth+1, 0,23,59,59);
      let startDate = formatDate(monthStartDate, 'yyyy-MM-dd hh:mm:ss');
      let endDate = formatDate(monthEndDate, 'yyyy-MM-dd hh:mm:ss');
      this.listQuery.createTime = [startDate,endDate];
      this.getList();
      this.getUserOptionList();
      this.getSupplierList();
      this.getGoodsList()
    },
    filters: {
      fifTakeState(val){
        if(val == 0){
          return '未安排提货'
        }else if(val == 1){
          return '已部分安排提货'
        }else if(val == 2){
          return '已安排全部提货'
        }
      },
      formatCreateTime(time) {
        if(time){
          let date = new Date(time);
          return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
        }else{
          return '--'
        }
      },
      fiferPayState(val){
        if(val == 0){
          return '--'
        }else if(val == 1){
          return '未结清'
        }else if(val == 2){
          return '已结清'
        }
      },
      fiftransactionType(val){
        if(val == 'BANK_PAY'){
          return '银行汇款'
        }else if(val == 'COD_PAY'){
          return '货到付款'
        }else if(val == 'DEPOSIT_PAY'){
          return '定金'
        }else{
          return '其它'
        }
      },
      fifpayState(val){
        if(val == 0){
          return '未支付'
        }else if(val == 1){
          return '部分支付'
        }else if(val == 2){
          return '已支付'
        }
      },
      fifplanstatus(cellValue){
        if(cellValue == 0){
          return '待物流发货'
        }else if(cellValue == 5){
          return '已取消'
        }else if(cellValue == 10){
          return '发货中'
        }else if(cellValue == 20){
          return '待安排司机'
        }else if(cellValue == 25){
          return '待提货'
        }else if(cellValue == 30){
          return '待出库'
        }else if(cellValue == 40){
          return '已出库'
        }
      }
    },
    methods:{
      handleSelectGoodsSn(item){
        this.listQuery.goodsSn = item.goodsSn
      },
      getGoodsList(){
        orderGoodsList().then((res)=>{
          this.goodsList = res.list
        })
      },
      querySearchGoodsSn(queryString, cb){
        let restaurants = this.goodsList;
        let results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
        // 调用 callback 返回建议列表的数据
        cb(results);
      },
      createFilter(queryString) {
        return (restaurant) => {
          return (restaurant.goodsSn.indexOf(queryString)!=-1);
        };
      },
      showList(item){
        this.dialogVisible6 = true;
        this.phlistLoading = true;
        planGoodsList({purchaseOrderId :item.orderId}).then((res)=>{
            this.phlist = res
            this.phlistLoading = false
        }).catch(()=>{
            this.phlistLoading = false
        })
      },
      //显示备注修改
      showRemark(item){
        this.changeRemarkFrom.pogId = item.pogId;
        this.changeRemarkFrom.goodsRemark = item.goodsRemark;
        this.dialogVisible5 = true;
      },

      //关闭备注弹窗
      handleClose5(){
        this.dialogVisible5 = false;
        this.$refs.changeRemarkFrom.clearValidate();
      },
      //提交备注
      handleConfirm5(){
        this.$refs['changeRemarkFrom'].validate((valid) => {
          if (valid) {
            this.btnLoading6 = true;
            let data = {};
            data.detailList = [];
            data.detailList.push(this.changeRemarkFrom)
            changeDetailRemarkPurchase(data).then(()=>{
              this.btnLoading6 = false;
              this.dialogVisible5 = false;
              this.$message({
                message: '修改成功',
                type: 'success'
              });
              this.getList()
            }).catch(()=>{
              this.btnLoading6 = false;
            })
          }
        })
      },
      showpop(item){
        this.dialogVisible = true;
        this.sendForm = JSON.parse(JSON.stringify(defaultSendForm));
        this.sendForm.max = item.goodsNum;
        this.sendForm.pogId = item.pogId;
      },

      handleConfirm(){
        this.$refs['sendForm'].validate((valid) => {
          if (valid) {
            this.btnLoading2 = true;
            let pa = {};
            pa.pogId = this.sendForm.pogId;
            pa.goodsTakeNum = this.sendForm.num;
            changePlanNum(pa).then(()=>{
              this.btnLoading2 = false;
              this.dialogVisible = false;
              this.getList();
            }).catch(()=>{
              this.btnLoading2 = false;
            })
          }
        })
      },

      //下载excle
      downloadExcel(){
        let params = JSON.parse(JSON.stringify(this.listQuery));
        params.isExport = 1;
        this.btnloading = true;
        purchaseOrderGoodsList(params).then((res)=>{
          this.btnloading = false;
          require.ensure([], () => {
            const { export_json_to_excel } = require('sheet/Export2Excel');
            const tHeader = res.title;
            const filterVal = res.columns;
            const list = res.list;
            const data = this.formatJson(filterVal, list);
            export_json_to_excel(tHeader, data, res.fileName);
          })
        }).catch(()=>{
          this.btnloading = false;
        })
      },

      //下载表格数据格式化
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => v[j]))
      },
      //去详情页
      toDetail(item){
        let routeData = this.$router.resolve({name:'purchaseContractDetail',query:{id:item.orderId}});
        window.open(routeData.href);
      },
      //商品
      remoteMethod(query) {
        if (query !== '') {
          this.loading = true;
          this.loading = false;
          goodsList({keywords:query}).then((res)=>{
            this.options = res.list;
          })
        } else {
          this.options = [];
        }
      },

      //供应商
      getSupplierList() {
          supplierList().then((res)=>{
            this.options2 = res;
          })
      },

      //获取员工下拉选项
      getUserOptionList(){
        getOrderUsersList().then((res)=>{
          this.userOptionList = res;
        })
      },

      //选择员工名称
      handleSelectUserName(key,item){
        this.listQuery[key] = item.userId;
      },

      //客户名称输入匹配
      querySearch(queryString, cb){
        getCustomerOption({keywords:queryString}).then((res)=>{
          cb(res);
        })
      },

      //选择客户名称
      handleSelectCustomerName(item){
        this.listQuery.keywords = item.customerName
      },

      /**
       * 切换选择状态
       */
      handleSelect(key, keyPath){
        this.listQuery.tab = key;
        if(key != 'my' && key != 'all'){
          this.listQuery.state = null;
        }
        this.handleSearchList();
      },
      handleSizeChange(val){
        this.listQuery.pageNum = 1;
        this.listQuery.pageSize = val;
        this.getList();
      },
      handleCurrentChange(val){
        this.listQuery.pageNum = val;
        this.getList();
      },

      handleSearchList(){
        this.listQuery.pageNum = 1;
        this.getList();
      },

      //获取订单列表
      getList() {
        this.listLoading = true;
        purchaseOrderGoodsList(this.listQuery).then(response => {
          this.tableData = response.list;
          this.count = response.count;
          this.statisticsAmount = response.statisticsAmount;
          this.statisticsGoodsNum = response.statisticsGoodsNum;
          this.authNum = response.authNum;
          this.closeNum = response.closeNum;
          this.authPrice = response.authPrice
          this.listLoading = false;
        }).catch(()=>{
          this.listLoading = false;
        });
      },
    },
  }
</script>

<style scoped lang="scss">

</style>
